package com.mcflywzx.airhockey.objects;

import static android.opengl.GLES20.GL_TRIANGLE_FAN;
import static android.opengl.GLES20.glDrawArrays;
import static android.opengl.GLES20.glDeleteTextures;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;

import com.mcflywzx.airhockey.Constants;
import com.mcflywzx.airhockey.data.VertexArray;
import com.mcflywzx.airhockey.programs.TextureShaderProgram;
import com.mcflywzx.airhockey.util.TextureHelper;

public class Text {
	
	private static final int POSITION_COMPONENT_COUNT = 2; //一个顶点有两个分量
	private static final int TEXTURE_COORDINATES_COMPONENT_COUNT = 2;
	private static final int STRIDE = (POSITION_COMPONENT_COUNT + TEXTURE_COORDINATES_COMPONENT_COUNT) * Constants.BYTES_PER_FLOAT;
	
	private final VertexArray va;
	
	public int tex = 0;
	
	public Text(float w, float h, String[] showText) {

		setTextTex(showText);
		va = new VertexArray(new float[] {
				//X,Y,S,T
				0f, 0f, 0.5f, 0.5f,
				-(w/2), -(h/2), 0f, 1f,
				w/2, -(h/2), 1f, 1f,
				w/2, h/2, 1f, 0f,
				-(w/2), h/2, 0f, 0f,
				-(w/2), -(h/2), 0f, 1f
		});
	}
	
	public void bindData(TextureShaderProgram tsp) {
		va.setVertexAttribPointer(
				0,
				tsp.getPositionAttributeLocation(),
				POSITION_COMPONENT_COUNT,
				STRIDE);
		
		va.setVertexAttribPointer(
				POSITION_COMPONENT_COUNT,
				tsp.getTextureCoordinatesAttributeLocation(),
				TEXTURE_COORDINATES_COMPONENT_COUNT, 
				STRIDE);
	}
	
	public int setTextTex(String[] showText) {
		//Delet useless OpenGL texture resource
		if(tex != 0) {
			int[] Dtex = new int[1];
			Dtex[0] = tex;
			glDeleteTextures(1, Dtex, 0);
		}
		
		Bitmap text = Bitmap.createBitmap(256,64, Bitmap.Config.ARGB_8888); 
		//图象大小要根据文字大小算下,以和文本长度对应 

		Canvas canvasTemp = new Canvas(text); 

		canvasTemp.drawColor(Color.argb(255, 20, 112, 147));

		Paint p = new Paint(); 

		p.setColor(Color.BLACK); 
		p.setAntiAlias(true);//此函数是用来防止边缘的锯齿，
		p.setTextSize(22); 

		for(int i = 0; i < showText.length; i ++) {
			canvasTemp.drawText(showText[i],0, 20 + i * 20,p); 
		}

		canvasTemp.save();
		
		tex = TextureHelper.loadTexture(text);
		
		return tex;

	}
	
	public void draw() {
		glDrawArrays(GL_TRIANGLE_FAN, 0, 6);
	}
}

